/*
 * @Author: Wangtao
 * @Date: 2022-09-01 15:28:34
 * @LastEditors: Wangtao
 * @LastEditTime: 2022-09-22 10:02:05
 */
import { defineStore } from 'pinia'

import io from 'socket.io-client'

import { refreshWsToken } from '@/common/apis/user'

import { userModule } from '@/common/store/modules/user'
import {
  dialOut,
  hangup,
  getAgentPhoneBarList,
  setAgentStatus,
  muteOrUnMute,
  holdOrUnHold,
  transfer,
  satisfaction,
  consult,
  cancelConsult,
  stopConsult,
  resumeConsult,
  consultTransfer,
  threeWayCall,
  webRtcRegisterInfo
} from '@/app/base/apis/call'
import { callCardModule } from '@/common/store/modules/call-card'

import WebPhoneSdk from './webrtc/webPhoneSdk'

export const callStateModule = defineStore('callState', {
  state: () => {
    return {
      webPhone: null,
      loginType: ''
    }
  },
  actions: {
    async initConnect(eventListenersObj: any) {
      const { data } = await refreshWsToken()
      const USERMODULE: any = userModule()
      const CALLCARD = callCardModule()
      const pushServer: any = USERMODULE.pushServer
      const url = pushServer[0].url
      const loginType = this.getLoginType()
      const socketData = {
        reconnectionDelay: 3000,
        query: {
          agentId: USERMODULE.agent._id,
          agentNumber: USERMODULE.agent.agentNumber,
          accountId: USERMODULE.agent.accountId,
          token: data.wsToken,
          wsExtra: JSON.stringify({
            loginType: loginType,
            channelType: 'WEB',
            ability: ['call']
          }),
          timestamp: data.timestamp,
          clientType: USERMODULE.clientType || 0
        },
        'force new connection': true,
        transports: ['websocket'],
        timeout: 5000
      }
      const socket = (io as any).connect(`${url}`, socketData)
      socket.on('connect_error', (e: any) => {
        console.log('connect_error', e)
      })
      socket.on('connect', () => {
        console.log('connect')
      })
      socket.on('callEvent', (data: any) => {
        if (data.type === 'loginStatus') {
          this.loginType = data.body.loginType
          if (eventListenersObj && eventListenersObj.success) {
            if (data.body.loginType === 'WEBRTC') {
              this.connect()
            }
            eventListenersObj.success(data.body)
          }
        } else if (data.type === 'callStatus') {
          if (eventListenersObj && eventListenersObj.message) {
            CALLCARD.oprateInfoByCallStateInfo(data.body)
            eventListenersObj.message(data)
          }
        }
      })
      socket.on('event', (data: any) => {
        eventListenersObj.message(data)
      })
      socket.on('error', (data: any) => {
        console.log('push connection error' + JSON.stringify(data))
      })
    },
    getLoginType() {
      const USERMODULE: any = userModule()
      let currentLoginType: any = ''
      const defaultLoginTypeList = ['WEBRTC', 'PSTN', 'SIP']
      const loginTypeList = USERMODULE.agent.agentCallConfig.loginType || []
      defaultLoginTypeList.some((type) => {
        if (loginTypeList.includes(type)) {
          currentLoginType = type
          return true
        }
      })
      return currentLoginType
    },
    async dialOut(dialoutNumber: string) {
      const USERMODULE = userModule()
      const res = await dialOut({
        loginType: this.loginType,
        calleeNumber: dialoutNumber,
        agentId: USERMODULE.agent._id,
        agentNumber: USERMODULE.agent.agentNumber,
        accountId: USERMODULE.agent.accountId
      })
      console.log(res)
    },
    async hangup() {
      const USERMODULE = userModule()
      const res = await hangup({
        agentId: USERMODULE.agent._id,
        agentNumber: USERMODULE.agent.agentNumber,
        accountId: USERMODULE.agent.accountId
      })
    },
    async muteOrUnMute(data: any) {
      return await muteOrUnMute(data)
    },
    async holdOrUnHold(type: string) {
      return await holdOrUnHold({
        type
      })
    },
    async transfer(data: any) {
      return await transfer(data)
    },
    async satisfaction(type: string) {
      return await satisfaction({
        type
      })
    },
    async consult(data: any) {
      return await consult(data)
    },
    async cancelConsult() {
      return await cancelConsult({})
    },
    async stopConsult() {
      return await stopConsult({})
    },
    async resumeConsult() {
      return await resumeConsult({})
    },
    async consultTransfer() {
      return await consultTransfer({})
    },
    async threeWayCall() {
      return await threeWayCall({})
    },
    async getAgentPhoneBarList() {
      const res: any = await getAgentPhoneBarList({})
      return res.data
    },
    async setAgentStatus(data: any) {
      const USERMODULE = userModule()
      const res: any = await setAgentStatus({
        agentNumber: USERMODULE.agent.agentNumber,
        accountId: USERMODULE.agent.accountId,
        statusNumber: data.statusNumber + ''
      })
      return res.data
    },
    async initWebrtcEvent() {
      const webRecInfo = await webRtcRegisterInfo({})
      // console.log(webRecInfo, 'oooooooo');
      // (this as any).webPhone = new WebPhoneSdk({ server: extras.sipRegisterAddress, sip: V7Softphone.agentInfo.webrtcSipNumber, secret: V7Softphone.agentInfo.webrtcSipKey })
      if (webRecInfo.success) {
        ;(this as any).webPhone = new WebPhoneSdk({
          // server: 'mc-dev-webrtc.7moor.com:1443',
          server: webRecInfo.data.wssUrl,
          sip: webRecInfo.data.sip,
          secret: webRecInfo.data.password
        })
        ;(this as any).webPhone.message = (res: any) => {
          console.log(res)
        }
      }
    },
    accept() {
      if (this.webPhone) {
        WebPhoneSdk.accept()
      }
    },
    connect() {
      if (!(this as any).webPhone || !this.isConnected()) {
        this.initWebrtcEvent()
      }
    },
    disconnect() {
      if ((this as any).webPhone && this.isConnected()) {
        WebPhoneSdk.disconnect()
      }
    },
    isConnected() {
      return (this as any).webPhone && WebPhoneSdk.isConnected()
    },
    sendDTMF(tone: string) {
      WebPhoneSdk.sendDTMF(tone)
    },
    updateLoginType (type: any) {
      this.loginType = type
    }
  }
})
